package com.sk.ccflower.server.lib.dbUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.sk.ccflower.lib.define.Consts;

public class DBConnection {
	
	protected Connection m_con = null;
	private String m_jdbc_url = null;
	private String m_user = null;
	private String m_password = null;
	
	public DBConnection() throws ClassNotFoundException {
		this(null, null, null);
	}
	
	public DBConnection( Connection conn ) throws ClassNotFoundException {
		this.m_con = conn;
	}
	
	public DBConnection(String jdbc_url) throws ClassNotFoundException {
		this(jdbc_url, null, null);
	}
	
	public DBConnection(String jdbc_url, String user, String password) throws ClassNotFoundException {
		Class.forName( Consts.JDBC_CLASS_NAME );

		setJdbcURL( jdbc_url );
		setUser( user, password );
	}
	
	public void setJdbcURL(String jdbc_url) {
		m_jdbc_url = new String(jdbc_url);
	}

	public void setUser(String user, String password) {
		m_user = new String(user);
		m_password = new String(password);
	}

	public Connection getConnection() {
		return m_con;
	}

	public Connection connect() throws SQLException {
		return connect(false);
	}

	public Connection connect(boolean transaction) throws SQLException {
		if (m_con == null) {
			m_con = DriverManager.getConnection(m_jdbc_url, m_user, m_password);
			m_con.setAutoCommit(transaction);
		}

		return m_con;
	}

	public Connection connect(boolean transaction, int retryCnt)
			throws SQLException {
		for (int i = 0; i < retryCnt; i++) {
			try {
				if (connect(transaction) != null) {
					return m_con;
				}
			} catch (SQLException e) {
				if (i + 1 == retryCnt)
					throw e;

				try {
					Thread.sleep(10 * 1000);
				} catch (InterruptedException ex) {
				}

			}
		}

		return m_con;
	}

	public void close() {
		try {
			if (m_con != null)
				m_con.close();
		} catch (SQLException ex) {
			ex.printStackTrace();
		}

		m_con = null;
	}

}
